<template>
  <div class="sys-section-bg">
    <div style="height:32px;"></div>
    <el-row :gutter="20" class="sys-stat-row">
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#409EFF" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">成员总数</div>
              <div class="stat-value">{{ members.length }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#67C23A" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">在职成员</div>
              <div class="stat-value">{{members.filter(m => m.status === '在职').length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#E6A23C" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">离职成员</div>
              <div class="stat-value">{{members.filter(m => m.status === '离职').length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#F56C6C" size="22"><i-ep-user /></el-icon>
            <div class="stat-info">
              <div class="stat-title">部门数</div>
              <div class="stat-value">{{[...new Set(members.map(m => m.department))].length}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider content-position="left">成员列表</el-divider>
    <div class="page-title">
      <el-icon><i-ep-user /></el-icon>
      <span style="margin-left: 8px; font-size: 20px; font-weight: bold;">成员管理</span>
    </div>
    <div class="toolbar">
      <el-input v-model="search" placeholder="请输入成员姓名/邮箱" style="width: 240px; margin-right: 16px;" clearable />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="openAddDialog" style="margin-left: 16px;">添加成员</el-button>
    </div>
    <el-table :data="pagedMembers" style="width: 100%; margin-top: 16px;" v-loading="loading">
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="department" label="部门" />
      <el-table-column prop="role" label="角色" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '在职' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next, jumper" :total="filteredMembers.length" :page-size="pageSize"
      :current-page="currentPage" @current-change="handlePageChange"
      style="margin-top: 16px; text-align: right;" />
    
    <!-- 添加/编辑成员弹窗 -->
    <el-dialog :title="dialogMode === 'add' ? '添加成员' : '编辑成员'" v-model="dialogVisible" width="500px" @close="resetDialog">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dialogForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="dialogForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'add'" label="密码" prop="password">
          <el-input v-model="dialogForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="dialogForm.department" placeholder="请选择部门" style="width: 100%;">
            <el-option label="技术部" value="技术部" />
            <el-option label="产品部" value="产品部" />
            <el-option label="设计部" value="设计部" />
            <el-option label="运营部" value="运营部" />
            <el-option label="市场部" value="市场部" />
            <el-option label="人事部" value="人事部" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="dialogForm.role" placeholder="请选择角色" style="width: 100%;">
            <el-option label="开发工程师" value="开发工程师" />
            <el-option label="产品经理" value="产品经理" />
            <el-option label="UI设计师" value="UI设计师" />
            <el-option label="运营专员" value="运营专员" />
            <el-option label="市场专员" value="市场专员" />
            <el-option label="人事专员" value="人事专员" />
            <el-option label="项目经理" value="项目经理" />
            <el-option label="技术总监" value="技术总监" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dialogForm.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="在职" value="在职" />
            <el-option label="离职" value="离职" />
            <el-option label="试用期" value="试用期" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDialog" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

// 成员管理数据
const members = ref([])
const loading = ref(false)
const search = ref('')
const pageSize = ref(10)
const currentPage = ref(1)

// 获取成员数据（对接后端）
async function fetchMembers() {
  loading.value = true
  try {
    const res = await axios.get(getApiUrl('/user/tree'), {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (res.data && Array.isArray(res.data)) {
      members.value = res.data.map(user => ({
        id: user.id,
        name: user.name || user.username,
        email: user.email,
        department: user.department || '技术部',
        role: user.role || '开发工程师',
        status: user.status || '在职'
      }))
    } else {
      members.value = []
    }
    console.log('获取到的成员数据:', members.value)
  } catch (e) {
    console.error('获取成员失败:', e)
    ElMessage.error('获取成员失败: ' + (e.response?.data || e.message))
    members.value = []
  }
  loading.value = false
}

// 创建用户
async function createUser(userData) {
  try {
    const res = await axios.post(getApiUrl('/user/create'), {
      username: userData.name,
      email: userData.email,
      phone: userData.phone || '',
      password: userData.password || '123456',
      department: userData.department,
      role: userData.role,
      status: userData.status
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (res.data && res.data.user) {
      const newUser = {
        id: res.data.user.id,
        name: res.data.user.username,
        email: res.data.user.email,
        department: userData.department,
        role: userData.role,
        status: userData.status
      }
      members.value.push(newUser)
      ElMessage.success('添加成功')
      return true
    }
  } catch (e) {
    console.error('创建用户失败:', e)
    ElMessage.error('创建用户失败: ' + (e.response?.data || e.message))
    return false
  }
}

// 更新用户
async function updateUser(userData) {
  try {
    const res = await axios.put(getApiUrl('/user/update'), {
      id: userData.id,
      username: userData.name,
      email: userData.email,
      phone: userData.phone || '',
      department: userData.department,
      role: userData.role,
      status: userData.status
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (res.data && res.data.user) {
      const idx = members.value.findIndex(m => m.id === userData.id)
      if (idx !== -1) {
        members.value[idx] = {
          id: userData.id,
          name: userData.name,
          email: userData.email,
          department: userData.department,
          role: userData.role,
          status: userData.status
        }
      }
      ElMessage.success('编辑成功')
      return true
    }
  } catch (e) {
    console.error('更新用户失败:', e)
    ElMessage.error('更新用户失败: ' + (e.response?.data || e.message))
    return false
  }
}

// 删除用户
async function deleteUser(userId) {
  try {
    const res = await axios.delete(getApiUrl(`/user/delete/${userId}`), {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (res.status === 200) {
      const idx = members.value.findIndex(m => m.id === userId)
      if (idx !== -1) {
        members.value.splice(idx, 1)
      }
      ElMessage.success('删除成功')
      return true
    }
  } catch (e) {
    console.error('删除用户失败:', e)
    ElMessage.error('删除用户失败: ' + (e.response?.data || e.message))
    return false
  }
}

// 搜索过滤和分页
const searchKeyword = ref('')
const filteredMembers = computed(() => {
  if (!searchKeyword.value) return members.value
  return members.value.filter(m =>
    m.name.includes(searchKeyword.value) ||
    m.email.includes(searchKeyword.value)
  )
})
const pagedMembers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredMembers.value.slice(start, start + pageSize.value)
})

function handleSearch() {
  searchKeyword.value = search.value
  currentPage.value = 1
}

// 添加/编辑弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('add')
const dialogForm = ref({ 
  id: null, 
  name: '', 
  email: '', 
  phone: '',
  password: '',
  department: '技术部', 
  role: '开发工程师', 
  status: '在职' 
})
const dialogFormRef = ref(null)
const submitLoading = ref(false)
const dialogRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

function openAddDialog() {
  dialogMode.value = 'add'
  Object.assign(dialogForm.value, { 
    id: null, 
    name: '', 
    email: '', 
    phone: '',
    password: '',
    department: '技术部', 
    role: '开发工程师', 
    status: '在职' 
  })
  dialogVisible.value = true
  nextTick(() => dialogFormRef.value && dialogFormRef.value.clearValidate())
}

function openEditDialog(row) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm.value, { 
    ...row,
    password: ''
  })
  dialogVisible.value = true
  nextTick(() => dialogFormRef.value && dialogFormRef.value.clearValidate())
}

function resetDialog() {
  Object.assign(dialogForm.value, { 
    id: null, 
    name: '', 
    email: '', 
    phone: '',
    password: '',
    department: '技术部', 
    role: '开发工程师', 
    status: '在职' 
  })
}

async function submitDialog() {
  dialogFormRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      let success = false
      
      if (dialogMode.value === 'add') {
        success = await createUser(dialogForm.value)
      } else {
        success = await updateUser(dialogForm.value)
      }
      
      if (success) {
        dialogVisible.value = false
        await fetchMembers()
      }
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确定要删除成员 ${row.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const success = await deleteUser(row.id)
    if (success) {
      await fetchMembers()
      nextTick(() => {
        if (pagedMembers.value.length === 0 && currentPage.value > 1) {
          currentPage.value--
        }
      })
    }
  } catch (error) {
    console.log('用户取消删除')
  }
}

function handlePageChange(page) {
  currentPage.value = page
}

onMounted(() => {
  fetchMembers()
})
</script>

<style scoped>
/* 系统管理内容区美化 */
.sys-section-bg {
  background: linear-gradient(135deg, #f8fafc 0%, #e6ecf5 100%);
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 64, 255, 0.06);
  padding: 32px 32px 24px 32px;
  margin-bottom: 24px;
  min-height: 600px;
  max-width: 1400px;
  width: 92vw;
  margin-left: auto;
  margin-right: auto;
}

/* 统计行和卡片样式 */
.sys-stat-row {
  margin-bottom: 24px;
}

.sys-stat-card {
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}

/* 统计卡片样式 */
.stat-card {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-info {
  margin-left: 16px;
}

.stat-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 4px 0;
}
</style> 